import java.util.*;

/**
 * @author LKQ
 * @date 2022/5/17 20:57
 * @description 逆序遍历
 */
public class Solution3 {
    public static void main(String[] args) {

    }

    public String reverseWords(String s) {
        char[] res = new char[s.length() + 1];
        char[] ch = s.toCharArray();
        int index = 0;
        int i = ch.length - 1;
        while (i >= 0) {
            while (i >= 0 && ch[i] == ' ') {
                i--;
            }
            int right = i;
            while (i >= 0 && ch[i] != ' ') {
                i--;
            }
            int left = i;
            for (int j = left + 1; j <= right; j++) {
                res[index++] = ch[j];
                if (j == right) {
                    //在每个单词最后加上空格
                    res[index++] = ' ';
                }
            }
        }
        return new String(res, 0, index - 1);
    }
}
